import React, { useState, useEffect,useContext } from 'react';
import { Form, Input, Button, message } from 'antd';
import axios from 'axios';
import './LoginPage.scss';
import { getCodeImg } from '../api/login';
import { login as loginAction } from '../store/actions/user';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { generateRoutes } from '../store/actions/permission';
import { getUserInfo } from '../store/actions/user';
import { DictContext } from '../context/context';

const LoginPage = () => {
  const [captchaImg, setCaptchaImg] = useState('');
  const [uuid, setUuid] = useState('');
    // 使用 useDispatch 来获取 dispatch 方法
    const dispatch = useDispatch();
    const navigate = useNavigate();

    const { getSystemName } = useContext(DictContext);
  useEffect(() => {
    loadCaptcha();
  }, []);

  const onFinish = async (values) => {
    try {
        //console.log('====login====',values);
        //console.log('====uuid====', uuid);
        const { username, password ,captcha } = values;
        
        //console.log('====login====',username, password ,captcha);
        // 调用 dispatch 方法来触发 login action
        const success = await dispatch(loginAction({ username, password, code:captcha, uuid }));
        if (success) {
          message.success('登录成功');
          dispatch(getUserInfo()).then(() =>{
            dispatch(generateRoutes()).catch(err => {
              //跳转到登陆页面
              navigate('/login', { replace: true });
            });
          }).catch(err => {
            //跳转到登陆页面
            navigate('/login', { replace: true });
          });
          navigate('/');
        } else {
          message.success('登录失败');
          navigate('/login');
        }
      // 假设后端有一个 /api/login 接口
      //await axios.post('/api/login', values);
    } catch (error) {
      message.error('Failed to login');
      navigate('/login');
    }
  };

  const loadCaptcha = async () => {
    const response = await getCodeImg();
    console.log('====response====',response)
    setUuid(response.uuid);
    //console.log(response);
    //setCaptchaImg(`data:image/png;base64,${response.img}`);   //java代码
    //go 使用 response.img 设置验证码图片
    setCaptchaImg(response.img);  //go代码
  };

  return (
    <div className="login-page">
      <div className="login-container">
        {/* 添加的文本 */}
        <div className="system-info">由{getSystemName()}提供</div>
        <Form onFinish={onFinish}>
          {/* 表单项 */}
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
            <Input.Password placeholder="密码" />
          </Form.Item>
          <Form.Item name="captcha" rules={[{ required: true, message: '请输入验证码!' }]} className="captchaWrapper">
          <div className="input-group">
            <Input placeholder="验证码" style={{ flex: '1', marginRight: '8px'}} />
            <img src={captchaImg} onClick={loadCaptcha} alt="captcha"  className="captchaImage"/>
            </div>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
          {/* 验证码 */}
        </Form>
      </div>
    </div>
  );
};
export default LoginPage